﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Goalchee.Common;
using Goalchee.DataModel;
using Windows.UI.Xaml.Navigation;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.System;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Goalchee
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class Landing : LayoutAwarePage
    {
        bool isEventRegistered;
        private const string ThingsUrl = "http://www.43Things.com/service/";
        private const string SearchGoals = "search_goals";
        private const string Apikey = "545008@43rtF0IcpguS2";
        DataServiceCall dataService = new DataServiceCall();

        public Landing()
        {
            this.InitializeComponent();
            CreateSettingsFlyout();
            Task<string> x = dataService.GetPopularTags();
            //resultsListView.ItemsSource = dataService.ReadPopularTags ( x );
            //<HyperlinkButton Content="HyperlinkButton" HorizontalAlignment="Left" VerticalAlignment="Top"/>
            RenderPanel(dataService.ReadPopularTags(x));
        }

        private void CreateSettingsFlyout()
        {
            if (!this.isEventRegistered)
            {
                // Listening for this event lets the app initialize the settings commands and pause its UI until the user closes the pane.
                // To ensure your settings are available at all times in your app, place your CommandsRequested handler in the overridden
                // OnWindowCreated of App.xaml.cs
                SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;
                this.isEventRegistered = true;
            }
        }

        private void RenderPanel(List<Tag> readSearchTags)
        {
            int count = 0;
            Random r = new Random(5);
            foreach (Tag readPopularTag in readSearchTags)
            {
                count++;
                Button hlButton = new Button
                {
                    Name = readPopularTag.TagName + count,
                    //NavigateUri = new Uri ( string.Format ( "{0}{1}?q={2}&api_key={3}", ThingsUrl, SearchGoals, readPopularTag.TagName, Apikey ), UriKind.Absolute ),
                    Content = readPopularTag.TagName,
                    FontSize = r.Next(10, 20),
                    Foreground = new SolidColorBrush(Colors.Black),
                    BorderThickness = new Thickness(5, 5, 5, 5),

                    Width = 150,
                    Height = 50,
                    CommandParameter = readPopularTag.TagName
                };
                hlButton.Click += hlButton_Click;
                itemsOne.Items.Add(hlButton);
            }
        }

        private void hlButton_Click(object sender, RoutedEventArgs e)
        {
            LoadState(((Windows.UI.Xaml.Controls.Primitives.ButtonBase)(sender)).CommandParameter, null);
            //this.Frame.Navigate ( typeof ( GoalsPerson ) );
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var queryText = navigationParameter as String;
            if (string.IsNullOrEmpty(queryText))
                return;
            //this.Frame.Navigate ( typeof ( GoalsPerson ), navigationParameter );
            this.Frame.Navigate(typeof(TagsGoal), navigationParameter);

            //Window.Current.Content = Frame;
            Window.Current.Activate();
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            // Added to make sure the event handler for CommandsRequested in cleaned up before other scenarios
            if (this.isEventRegistered)
            {
                SettingsPane.GetForCurrentView().CommandsRequested -= onCommandsRequested;
                this.isEventRegistered = false;
            }
        }

        void onSettingsCommand(IUICommand command)
        {
            SettingsCommand settingsCommand = (SettingsCommand)command;
            //this.NotifyUser("You selected the " + settingsCommand.Label + " settings command which originated from the " + SettingsPane.Edge.ToString(), NotifyType.StatusMessage);
        }

        void onCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            UICommandInvokedHandler handler = new UICommandInvokedHandler(onSettingsCommand);

            //SettingsCommand generalCommand = new SettingsCommand("generalSettings", "General", handler);
            //eventArgs.Request.ApplicationCommands.Add(generalCommand);

            //SettingsCommand helpCommand = new SettingsCommand("helpPage", "Help", handler);
            //eventArgs.Request.ApplicationCommands.Add(helpCommand);
        }
    }
}
